package com.hxkcloud.patient.aerotel.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;

import com.hxkcloud.patient.aerotel.AerotelActivity;
import com.hxkcloud.patient.aerotel.domain.health.HealthDeviceManager;
import com.hxkcloud.patient.aerotel.log.AppLogger;
import com.hxkcloud.patient.aerotel.util.ClsUtils;


/**
 * Created by zhangtaoshuai on 16/2/29.
 */
public class BTManager {
    private Context context = null;
    private BluetoothAdapter adapter = null;
    private BroadcastReceiver receiver = null;

    private String targetDeviceName = null;
//
    // 初始化
    public BTManager(Context context) {
        this.context = context;
        initAdapter();
        initRecevier();
    }
//
    private void initAdapter() {
        adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter == null) {
            Toast.makeText(context, "该设备不支持蓝牙！", Toast.LENGTH_SHORT).show();
            return;
        }
        enabledBT();
    }

    // 开启蓝牙
    private void enabledBT() {
        if (!adapter.isEnabled()) {
            Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            context.startActivity(mIntent);
        }
    }
    private void initRecevier() {
        if (receiver == null) {
            receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    BluetoothDevice device = intent
                            .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    String actionName = intent.getAction();
                    if (actionName.equals(BluetoothDevice.ACTION_FOUND)) {
                        // 如果找到的设备和想要搜索的设备名一致，就发送找到广播
                        if (device.getName() != null
                                && device.getName().contains(
                                targetDeviceName)) {
                            cancelDiscover();
                            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                                try {
                                    Toast.makeText(context, "尝试配对...",   Toast.LENGTH_SHORT).show();
                                    ClsUtils.createBond(BluetoothDevice.class, device);
                                    Thread.sleep(1000);
//                                    ClsUtils.setPin(BluetoothDevice.class, device, "39");
//                                    Thread.sleep(500);
//                                    ClsUtils.cancelPairingUserInput(BluetoothDevice.class, device);
                                    if (!HealthDeviceManager.exists(device.getAddress())) {
                                        HealthDeviceManager.reload();
                                        ((AerotelActivity) context).initDevices("请选择设备");
                                        Toast.makeText(context, "配对成功", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (Exception ex) {
                                    AppLogger.e("pairing", ex);
                                    Toast.makeText(context, "配对失败", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            } else {
                                Toast.makeText(context, "设备为已配对设备", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else if (actionName
                            .equals("android.bluetooth.adapter.action.DISCOVERY_FINISHED")) {
                        cancelDiscover();
                    } else if (actionName.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        switch (device.getBondState()) {
                            case BluetoothDevice.BOND_BONDING:
                                AppLogger.d("正在配对......");
                                Toast.makeText(context, "正在配对...", Toast.LENGTH_SHORT).show();
                                break;
                            case BluetoothDevice.BOND_BONDED:
                                AppLogger.d("完成配对");
                                Toast.makeText(context, "完成配对", Toast.LENGTH_SHORT).show();
                                break;
                            case BluetoothDevice.BOND_NONE:
                                AppLogger.d("取消配对");
                                Toast.makeText(context, "取消配对", Toast.LENGTH_SHORT).show();
                            default:
                                break;
                        }
                    }
                }
            };
        }
    }

    // 开始搜寻设备

    public void discover(String name) {
        if (adapter == null) {
            Toast.makeText(context, "未找到蓝牙硬件", Toast.LENGTH_SHORT).show();
            return;
        }
        targetDeviceName = name;
        if (adapter.isDiscovering()) {
            Toast.makeText(context, "正在搜索请等待...", Toast.LENGTH_SHORT).show();
        } else {
            // 注册广播
            IntentFilter filter = new IntentFilter();
            filter.addAction(BluetoothDevice.ACTION_FOUND);//android.bluetooth.device.action.FOUND
            filter.addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
            filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
            context.registerReceiver(receiver, filter);
            adapter.startDiscovery();
            Toast.makeText(context, "开始查找附近心电设备...", Toast.LENGTH_SHORT).show();
        }
    }

    // 停止搜索设备
    private void cancelDiscover() {
        // 如果还在搜寻设备，则停止
        if (adapter.isDiscovering()) {
            adapter.cancelDiscovery();
        }
        // 注销广播
        context.unregisterReceiver(receiver);
    }
}
